<template>
  <div class="exhibitor-management management-page">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 参展商列表 -->
    <el-card class="list-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="header-title">参展商列表</span>
            <el-tag type="info" class="header-count" size="small">
              共 {{ total }} 条
            </el-tag>
          </div>
          <div class="header-operations">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>添加展商
            </el-button>
            <el-button 
              type="danger" 
              :disabled="!selectedExhibitors.length"
              @click="handleBatchDelete"
            >
              <el-icon><Delete /></el-icon>
              批量删除 {{ selectedExhibitors.length ? `(${selectedExhibitors.length})` : '' }}
            </el-button>
          </div>
        </div>
      </template>
      <el-table :data="exhibitorList" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="展商图片" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.imageUrl"
              :preview-src-list="[row.imageUrl]"
              fit="cover"
              style="width: 80px; height: 80px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="展商名称" min-width="150" />
        <el-table-column prop="description" label="展商介绍" min-width="200" show-overflow-tooltip />
        <el-table-column label="展商视频" min-width="150">
          <template #default="{ row }">
            <div v-if="row.videoUrl" class="video-info">
              <el-button type="primary" link @click="previewVideo(row)">
                <el-icon><VideoPlay /></el-icon>预览视频
              </el-button>
              <el-button type="primary" link :href="row.videoUrl" target="_blank">
                <el-icon><Download /></el-icon>下载视频
              </el-button>
            </div>
            <span v-else>暂无视频</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑展商对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加展商' : '编辑展商'"
      width="600px"
    >
      <el-form
        ref="exhibitorFormRef"
        :model="exhibitorForm"
        :rules="exhibitorRules"
        label-width="100px"
      >
        <el-form-item label="展商名称" prop="name">
          <el-input v-model="exhibitorForm.name" placeholder="请输入展商名称" />
        </el-form-item>

        <el-form-item label="展商介绍" prop="description">
          <el-input
            v-model="exhibitorForm.description"
            type="textarea"
            rows="4"
            placeholder="请输入展商介绍"
          />
        </el-form-item>
        
        <el-form-item label="展商图片" prop="image">
          <el-upload
            class="exhibitor-upload"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept="image/*"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
          >
            <template #default>
              <el-button type="primary">选择图片</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传展商图片，只能上传 jpg/png 文件
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="展商视频" prop="video">
          <el-upload
            class="exhibitor-upload"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept="video/*"
            :on-change="handleVideoChange"
            :on-remove="handleVideoRemove"
            :before-upload="beforeVideoUpload"
          >
            <template #default>
              <el-button type="primary">选择视频</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                请上传展商视频，支持mp4等格式，大小不超过20MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus, Download, Delete, VideoPlay } from '@element-plus/icons-vue'
import { 
  getExhibitorList, 
  addExhibitor, 
  updateExhibitor, 
  deleteExhibitor,
  uploadExhibitorImage,
  uploadExhibitorVideo,
  deleteExhibitorImage,
  deleteExhibitorVideo
} from '@/api/exhibitor'
import type { ExhibitorDO } from '@/api/exhibitor'

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 表单数据
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const exhibitorFormRef = ref<FormInstance>()
const submitting = ref(false)

const exhibitorForm = reactive({
  id: 0,
  name: '',
  description: '',
  imageUrl: '',
  videoUrl: '',
  image: null as File | null,
  video: null as File | null
})

// 表单校验规则
const exhibitorRules = reactive<FormRules>({
  name: [{ required: true, message: '请输入展商名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入展商介绍', trigger: 'blur' }],
  image: [{
    validator: (rule, value, callback) => {
      if (dialogType.value === 'add' && !exhibitorForm.image) {
        callback(new Error('请上传展商图片'))
      } else if (dialogType.value === 'edit' && !exhibitorForm.image && !exhibitorForm.imageUrl) {
        callback(new Error('请上传展商图片'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }]
})

const loading = ref(false)
const exhibitorList = ref<ExhibitorDO[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedExhibitors = ref<ExhibitorDO[]>([])

// 获取展商列表
const fetchExhibitorList = async () => {
  loading.value = true
  try {
    const response = await getExhibitorList({
      page: currentPage.value,
      size: pageSize.value
    })
    exhibitorList.value = response.current_data
    total.value = response.total_record
  } catch (error) {
    console.error('获取展商列表失败:', error)
    ElMessage.error('获取展商列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchExhibitorList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  handleSearch()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchExhibitorList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchExhibitorList()
}

// 文件上传处理
const handleImageChange = (file: any) => {
  exhibitorForm.image = file.raw
}

const handleImageRemove = () => {
  exhibitorForm.image = null
}

// 视频上传前检查
const beforeVideoUpload = (file: File) => {
  const maxSize = 20 * 1024 * 1024 // 20MB
  if (file.size > maxSize) {
    ElMessage.error('视频大小不能超过20MB')
    return false
  }
  return true
}

// 视频上传处理
const handleVideoChange = (file: any) => {
  exhibitorForm.video = file.raw
}

const handleVideoRemove = () => {
  exhibitorForm.video = null
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (!size) return '0 B'
  if (size < 1024) return size + ' B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB'
  if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(2) + ' MB'
  return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
}

// 显示添加对话框
const showAddDialog = () => {
  dialogType.value = 'add'
  Object.assign(exhibitorForm, {
    id: 0,
    name: '',
    description: '',
    image: null,
    video: null
  })
  dialogVisible.value = true
}

// 编辑展商
const handleEdit = (row: ExhibitorDO) => {
  dialogType.value = 'edit'
  Object.assign(exhibitorForm, {
    id: row.id,
    name: row.name,
    description: row.description,
    imageUrl: row.imageUrl,
    videoUrl: row.videoUrl,
    image: null,
    video: null
  })
  dialogVisible.value = true
}

// 删除展商
const handleDelete = async (row: ExhibitorDO) => {
  try {
    await ElMessageBox.confirm('确定要删除该展商吗？', '提示', {
      type: 'warning'
    })
    await deleteExhibitor(row.id)
    ElMessage.success('删除成功')
    fetchExhibitorList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!exhibitorFormRef.value) return
  
  await exhibitorFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 准备表单数据
        const formData = {
          name: exhibitorForm.name,
          description: exhibitorForm.description,
          imageUrl: exhibitorForm.imageUrl,
          videoUrl: exhibitorForm.videoUrl
        }

        // 处理图片上传
        if (exhibitorForm.image) {
          try {
            const imageResponse = await uploadExhibitorImage(exhibitorForm.image)
            if (imageResponse.data && typeof imageResponse.data === 'string') {
              formData.imageUrl = imageResponse.data
            } else {
              throw new Error('图片上传失败')
            }
          } catch (error) {
            console.error('图片上传失败:', error)
            ElMessage.error('图片上传失败')
            return
          }
        } else if (dialogType.value === 'add') {
          ElMessage.error('请上传展商图片')
          return
        }

        // 处理视频上传
        if (exhibitorForm.video) {
          try {
            const videoResponse = await uploadExhibitorVideo(exhibitorForm.video)
            if (videoResponse.data && typeof videoResponse.data === 'string') {
              formData.videoUrl = videoResponse.data
            } else {
              throw new Error('视频上传失败')
            }
          } catch (error) {
            console.error('视频上传失败:', error)
            ElMessage.error('视频上传失败')
            return
          }
        }

        // 提交表单数据
        if (dialogType.value === 'add') {
          await addExhibitor(formData)
          ElMessage.success('添加成功')
        } else {
          await updateExhibitor(exhibitorForm.id, formData)
          ElMessage.success('更新成功')
        }
        
        dialogVisible.value = false
        fetchExhibitorList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 删除图片
const handleDeleteImage = async (exhibitorId: number) => {
  try {
    await deleteExhibitorImage(exhibitorId)
    ElMessage.success('图片删除成功')
    fetchExhibitorList()
  } catch (error) {
    console.error('图片删除失败:', error)
    ElMessage.error('图片删除失败')
  }
}

// 删除视频
const handleDeleteVideo = async (exhibitorId: number) => {
  try {
    await deleteExhibitorVideo(exhibitorId)
    ElMessage.success('视频删除成功')
    fetchExhibitorList()
  } catch (error) {
    console.error('视频删除失败:', error)
    ElMessage.error('视频删除失败')
  }
}

// 表格选择处理
const handleSelectionChange = (selection: ExhibitorDO[]) => {
  selectedExhibitors.value = selection
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedExhibitors.value.length) {
    ElMessage.warning('请选择要删除的参展商')
    return
  }

  ElMessageBox.confirm(
    `确认删除选中的 ${selectedExhibitors.value.length} 个参展商吗？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true
      for (const exhibitor of selectedExhibitors.value) {
        await deleteExhibitor(exhibitor.id)
      }
      ElMessage.success('批量删除成功')
      selectedExhibitors.value = []
      fetchExhibitorList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    } finally {
      loading.value = false
    }
  })
}

// 添加视频预览函数
const previewVideo = (row: ExhibitorDO) => {
  if (!row.videoUrl) return;
  
  // 创建视频预览对话框
  ElMessageBox.alert(
    `<div class="video-preview-container">
      <video 
        controls 
        style="width: 100%; max-width: 800px;"
        src="${row.videoUrl}"
      ></video>
    </div>`,
    '视频预览',
    {
      dangerouslyUseHTMLString: true,
      customClass: 'video-preview-dialog',
      showConfirmButton: false,
      showClose: true,
      center: true,
      callback: () => {}
    }
  )
}

onMounted(() => {
  fetchExhibitorList()
})
</script>

<style lang="scss" scoped>
@import '@/styles/common.scss';

.exhibitor-management {
  .exhibitor-logo {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .logo-placeholder {
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    border-radius: 4px;
    color: #909399;
  }

  .exhibitor-upload {
    @extend .upload-container;
  }

  .status-tag {
    min-width: 80px;
    text-align: center;
  }
}

:deep(.video-preview-dialog) {
  .el-message-box__content {
    padding: 20px;
    text-align: center;
  }
}

.video-info {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style> 